package com.sec.android.app.myfiles.fragment.home;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.feature.KnoxMgr;
import com.sec.android.app.myfiles.feature.SmartTipMgr;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.ModuleLoader;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.cloud.CloudFileHomeItem;
import com.sec.android.app.myfiles.module.local.category.CategoryHomeItem;
import com.sec.android.app.myfiles.module.local.recent.RecentHomeItem;
import com.sec.android.app.myfiles.module.shortcut.ShortcutHomeItem;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.SmartTipUtils;
import com.sec.android.app.myfiles.util.UiUtils;

import java.util.ArrayList;

public class HomeFragment extends AbsMyFilesFragment {
    private RecentHomeItem mRecentHomeItem;
    private CategoryHomeItem mCategoryHomeItem;
    protected ArrayList<HomeFragmentItem> mItemList;
    private HomeFragmentItem.SelectableItem mActionModeItem;
    protected ShortcutHomeItem mShortcutHomeItem;
    protected boolean mIsLeftPanel = false;
    private View mTipCardView;

    protected int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        int layoutResId = getLayoutId();
        return inflater.inflate(layoutResId, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        Context context = getActivity().getBaseContext();
        super.onViewCreated(view, savedInstanceState);
        mView = getView();
        mItemList = new ArrayList<>();

        ModuleLoader.getInstance().createHomeItem(context, this, mItemList, mIsLeftPanel);

        getHomeItems();
        ensureSecureFolderTipCard();
        setActionMode(ActionModeType.NORMAL);
    }

    public boolean canShowTipCard() {
        boolean ret = false;
        KnoxMgr knoxMgr = KnoxMgr.getInstance(mContext);
        if (SmartTipUtils.isNormalOwnerMode(mContext, mNavigationInfo) && knoxMgr.isSupportSecureFolder() && !knoxMgr.isInstallSecureFolder()) {
            ret = PreferenceUtils.getShowSecureFolderTipCard(mContext);
        }
        return ret;
    }

    private void ensureSecureFolderTipCard() {
        if (mView == null) {
            return;
        }

        if (canShowTipCard()) {
            mTipCardView = mView.findViewById(R.id.secure_folder_tip_card);
            if (mTipCardView != null) {
                mTipCardView.setVisibility(View.VISIBLE);
                ImageButton tipCardCloseButton = (ImageButton) mView.findViewById(R.id.tip_card_close);
                tipCardCloseButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mTipCardView.setVisibility(View.GONE);
                        PreferenceUtils.setShowSecureFolderTipCard(mContext, false);
                    }
                });

                Button tipCardMoreButton = (Button) mView.findViewById(R.id.tip_card_button);
                tipCardMoreButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mTipCardView.setVisibility(View.GONE);
                        PreferenceUtils.setShowSecureFolderTipCard(mContext, false);
                        Intent intent = new Intent("com.sec.knox.securefolder.CREATE_SECURE_FOLDER"); // secure folder setup intent
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("skip_popup", false);

                        try {
                            startActivity(intent);
                        } catch (ActivityNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                });

                setBtnBackgroundColor(tipCardMoreButton);
            }
        }
    }

    @Override
    public void setPathIndicatorDivider(ImageView pathIndicatorDivider) {
        if (pathIndicatorDivider != null) {
            pathIndicatorDivider.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        for (HomeFragmentItem homeItem : mItemList) {
            if (homeItem != null) {
                homeItem.onPause();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        for (HomeFragmentItem homeItem : mItemList) {
            if (homeItem != null) {
                homeItem.onResume();
            }
        }

        if (SmartTipUtils.canShowSmartTip(mContext)) {
            checkSmartTipCondition();
        }

        refreshTipCardView();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        for (HomeFragmentItem homeItem : mItemList) {
            if (homeItem != null) {
                homeItem.onDestroy();
            }
        }
        finishActionMode();
        mItemList.clear();
        mItemList = null;
    }


    protected void getHomeItems() {
        // This order is based on makeModuleChain in ModuleManager,
        // so order should not be changed.
        for (HomeFragmentItem h : mItemList) {
            if (h instanceof RecentHomeItem) {
                mRecentHomeItem = (RecentHomeItem) h;
            } else if (h instanceof CategoryHomeItem) {
                mCategoryHomeItem = (CategoryHomeItem) h;
            } else if (h instanceof ShortcutHomeItem) {
                mShortcutHomeItem = (ShortcutHomeItem) h;
                break;
            }
        }
    }

    @Override
    public void reload() {
        if (mShortcutHomeItem != null) {
            mShortcutHomeItem.reload();
        }
        if (mRecentHomeItem != null) {
            mRecentHomeItem.reload();
        }
    }

    @Override
    public int getListItemCount() {
        int recentHomeItemCount = 0;
        int shortcutHomeItemCount = 0;
        if (mRecentHomeItem == null && mShortcutHomeItem == null) {
            return super.getListItemCount();
        } else {
            if (mRecentHomeItem != null) {
                recentHomeItemCount = mRecentHomeItem.getTotalFileCount();
            }
            if (mShortcutHomeItem != null) {
                shortcutHomeItemCount = getShortcutListItemCount();
            }
            return recentHomeItemCount + shortcutHomeItemCount;
        }
    }

    public int getRecentItemCount() {
        if (mRecentHomeItem != null) {
            return mRecentHomeItem.getTotalFileCount();
        }
        return super.getRecentItemCount();
    }

    public int getShortcutListItemCount() {
        int nRet = 0;

        if (mShortcutHomeItem != null) {
            return mShortcutHomeItem.getTotalFileCount();
        }

        return nRet;
    }

    @Override
    public void setActionMode(ActionModeType actionMode) {
        boolean itemEnabled = true;

        if (actionMode != ActionModeType.NORMAL) {
            // if there is no item to want to action mode,
            // set the default item to recent.
            // (in case of More -> Edit).
            if (mActionModeItem == null && mRecentHomeItem != null) {
                mActionModeItem = mRecentHomeItem;
            }
            itemEnabled = false;
        }
        super.setActionMode(actionMode);
        boolean bShowCheckBox = false;
        switch (mActionModeType) {
            case SELECT_SHARE_FILE_OPERATION:
            case SELECT_FILE_FOLDER_OPERATION:
            case EDIT_FILE_FOLDER_OPERATION:
                bShowCheckBox = true;
                break;
            default:
                break;
        }
        setCheckMode(bShowCheckBox);
        setItemEnabled(itemEnabled);
        if (!mNavigationInfo.getIsSearchMode() && !mIsLeftPanel) {
            mActivity.invalidateOptionsMenu();
        }
    }

    public void setCheckMode(boolean bShow) {
        if (mActionModeItem != null) {
            if (mView != null) {
                if (bShow) {
                    mActionModeItem.setCheckMode(true);
                } else {
                    mActionModeItem.setCheckMode(false);
                    mActionModeItem = null;
                }
            }
        }
    }

    public void setItemEnabled(boolean itemEnabled) {
        if (mItemList != null) {
            for (HomeFragmentItem homeItem : mItemList) {
                if (homeItem != null) {
                    homeItem.setItemEnabled(itemEnabled);
                }
            }
        }
    }

    private void setBtnBackgroundColor(TextView v) {
        if (AppFeatures.isEnableButtonBackgrounds(mContext)) {
            int horizontalPadding = (int) getResources().getDimension(R.dimen.tip_card_button_ripple_padding_horizontal);
            int verticalPadding = (int) getResources().getDimension(R.dimen.tip_card_button_ripple_padding_vertical);
            v.setBackgroundResource(R.drawable.navigation_path_button);
            v.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding);
        }
    }

    @Override
    public FileRecord getFileRecord(int position) {
        return null;
    }

    @Override
    public ArrayList<FileRecord> getSelectedFile() {
        ArrayList<FileRecord> ret = null;
        if (mActionModeItem != null) {
            ret = mActionModeItem.getSelectedFile();
        }
        if (ret == null) {
            ret = new ArrayList<>();
        }
        return ret;
    }

    @Override
    public int getSelectedFileCount() {
        int nRet = 0;

        if (mRecentHomeItem != null) {
            nRet = mRecentHomeItem.getSelectedFileCount();
        }

        return nRet;
    }

    @Override
    public int getTotalFileCount() {
        int nRet = 0;

        if (mRecentHomeItem != null) {
            nRet = mRecentHomeItem.getTotalFileCount();
        }

        return nRet;
    }

    @Override
    public void selectAll(boolean select) {
        if (mRecentHomeItem != null) {
            if (select) {
                mRecentHomeItem.selectAll();
            } else {
                mRecentHomeItem.unselectAll();
            }
        }
    }

    @Override
    public void setEmptyView() {
    }

    @Override
    public void clearEmptyView() {
    }

    @Override
    public void setLoadingView() {
    }

    @Override
    public AbsListView getListView() {
        if (mShortcutHomeItem != null) {
            return mShortcutHomeItem.getShortcutListView();
        }
        return null;
    }

    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mRecentHomeItem != null) {
            mRecentHomeItem.updateRecentItemLayout();
        }
        if (mNavigationInfo.isPickerMode()) {
            if (mMenu != null) {
                mMenu.updateSelectAllCheckboxContainer();
            }
        }
        if (mCategoryHomeItem != null) {
            mCategoryHomeItem.updateCategoryItemLayout();
        }

        if (SmartTipUtils.canShowSmartTip(mContext)) {
            SmartTipMgr.getInstance(getActivity()).saveSmartTipStateBeforeRotate();
            SmartTipMgr.getInstance(getActivity()).saveSmartTipTypeBeforeRotate();
            Log.d(this, "onConfigurationChanged() ] Smart Tip's information is saved before rotating");
            if (AppFeatures.isNote()) {
                if (UiUtils.getScreenState(mContext) == AppConstants.LANDSCAPE) {
                    SmartTipMgr.getInstance(mActivity).clearSmartTipPopup();
                }
            } else {
                checkSmartTipCondition();
            }
        }
    }

    @Override
    public int getTotalCheckableFileCount() {
        return getTotalFileCount();
    }

    @Override
    protected void _onContentChanged(int event) {
    }

    @Override
    public void onLoadFinished() {
        // May not implement..
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK && mItemList != null) {
            CloudFileHomeItem item = null;
            for (HomeFragmentItem homeItem : mItemList) {
                if (homeItem instanceof CloudFileHomeItem) {
                    item = (CloudFileHomeItem) homeItem;
                    break;
                }
            }

            if (item != null) {
                item.enter(item.getDriveRecord(requestCode), false);
            }
        }
    }

    public boolean isContentsAtTop() {
        boolean ret = false;
        if (mView != null) {
            ScrollView scrollView = (ScrollView) mView.findViewById(R.id.scrollView);
            if (scrollView != null) {
                ret = scrollView.getScrollY() == 0;
            }
        }
        return ret;
    }

    private void refreshTipCardView() {
        if (mView == null || mTipCardView == null) {
            return;
        }

        if (canShowTipCard() && mTipCardView.getVisibility() == View.VISIBLE) {
            TextView tipCardTitle = (TextView) mTipCardView.findViewById(R.id.tip_card_title);
            tipCardTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, mContext.getResources().getDimensionPixelSize(R.dimen.tip_card_title_textsize));

            TextView tipCardText = (TextView) mTipCardView.findViewById(R.id.tip_card_text);
            tipCardText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mContext.getResources().getDimensionPixelSize(R.dimen.tip_card_text_textsize));

            Button tipCardBtn = (Button) mTipCardView.findViewById(R.id.tip_card_button);
            tipCardBtn.setTextSize(TypedValue.COMPLEX_UNIT_PX, mContext.getResources().getDimensionPixelSize(R.dimen.tip_card_button_textsize));
        }
    }
}
